package com.sky.service.impl;

import com.sky.context.UserHolder;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    // 查询地址簿列表
    @Override
    public List<AddressBook> findList(AddressBook addressBook) {
        return addressBookMapper.findList(addressBook);
    }

    // 新增地址
    @Override
    public void save(AddressBook addressBook) {
        //1 补齐参数(用户id和是否默认)
        /*Long userId = UserHolder.get();
        addressBook.setUserId(userId);*/
        addressBook.setUserId(UserHolder.get()); // 获取登录人id
        if (addressBook.getIsDefault() == null) {
            addressBook.setIsDefault(0); // 非默认为0
        }

        //2 调用mapper
        addressBookMapper.save(addressBook);


    }

    // 设置默认地址
    @Transactional //增 删 改多次, 必须事务控制
    @Override
    public void setDefault(AddressBook addressBook) {
        //1 设置所有地址簿为非默认
        Long userId = UserHolder.get();
        addressBookMapper.updateByUserId(userId);

        //2 设置当前地址簿为默认地址
        addressBook.setIsDefault(1);

        // 更新数据库
        addressBookMapper.update(addressBook);
    }


    // 根据ID回显地址信息
    public AddressBook findById(Long id) {
        return addressBookMapper.findById(id);
    }
    // 修改地址
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);

    }

    // 删除地址
    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);

    }
}
